<?php

namespace app\index\controller;

use controller\BasicWechat;
use app\comm\service\SendMsgService;
use app\comm\service\UserService;
use app\comm\service\SysToolsLevePoint;
use think\Controller;
use think\Cache;
use think\Db;
use think\Config;
use Endroid\QrCode\QrCode;
use app\index\service\WeixinService;
use app\comm\controller\WebIndexController;
use app\index\service\PointService;
class Outlo extends Controller {

	//登录首页
	public function index(){
		$uid = $this->getRandom(10);
		$data= ["uid"=>$uid,"openid"=>''];
		Db::table("ys_chart_uschart")->insert($data);
		$this->assign('uid',$uid);
		
		return view('outlo/index');
	}

	//微信扫码登录
	public function logobysc(){
		$uid = request()->get("uid");
		$restult = Db::table("ys_chart_uschart")->where('uid',$uid)->find();
		
		if($restult["openid"]!=''){
			$result = Db::table("ys_user")->where("openid",$restult["openid"])->find();
				$data =["mobile"   => $result["mobile"],
						"password" => $result["password"],
						'openid'   => $result["openid"],
						"uid"      =>  $result["uid"]];
			session('_user_uid_',$data);
			return json(["status"=>1,"data"=>"登录成功"]);
		}else{
			return json(["status"=>0,"data"=>"没有扫码"]);
		}
	}
	//绑定手机号码
	public function binduser(){
		if(request()->isPost()){
			$post = request()->post();
			$result = Db::table("ys_user")->where("mobile",$post["mobile"])->find();
			//空，就表示没有改手机号码
			
			if(is_null($result)){
				$mypoint = (new PointService())->Point(1);
				$data =[
					'mobile'     =>  $post['mobile'],
			   	    'password' 	 =>  MD5($post['password']),
			    	'openid'     =>  session('openid'),
			    	'addtime' 	 =>  time(),
				   	'pay_code' 	 =>  rand(1000,9999).time(),
				   	"nickname"	 =>	 $post['name'],
				   	"pay_points" =>	 $mypoint["point"],
				   	"level_point"=>  $mypoint["point"]
		    	];
		    	if(!empty(session("sharer"))){
				 	$data["pid"] = session("sharer");
				 	$pint = (new PointService())->Point(4);
				 	$pid 	= 	session("sharer");
				 	$user = (new PointService())->User($pid);
				 	Db::table("ys_user")->where("uid",$pid)->setInc("pay_points",$pint["point"]);
				 	Db::table("ys_user")->where("uid",$pid)->setInc("level_point",$pint["point"]);
				 	$datapoint = [
			 			"uid"      =>  $pid,
			 			"uidtype"  =>  3,	    			//1.为前台自己注册，2位后台操作.3推荐好友获得
			 			"signid"   =>  $pint["id"], 	    //积分规则id
			 			"type"     =>  1,					//类型，0消费，1增加
			 			"point"    =>  $pint["point"],		//变更积分数值（减少的时候数值前加上负号，如-100）
			 			"curpoint" =>  $user["pay_points"],	//当前积分
			 			"whname"   =>  '推荐好友的积分',	//操作者姓名，后台管理员或者前台会员
			 			"addtime"  =>	time(), 			//	addtime	
			 	
				 	 ];
				    //积分
				 	Db::table("ys_user_point_log")->insert($datapoint);
				 }


		    	 Db::table("ys_user")->insert($data);

		    	 $uid = Db::table("ys_user")->where("mobile",$post["mobile"])->find()["uid"];
		    	 $data["uid"] = $uid;
				 $datapoint = [
			 			"uid"      =>  $uid["uid"],
			 			"uidtype"  =>  1,	    			//1.为前台自己注册，2位后台操作.3推荐好友获得
			 			"signid"   =>  $mypoint["id"], 	    //积分规则id
			 			"type"     =>  1,					//类型，0消费，1增加
			 			"point"    =>  $mypoint["point"],	//变更积分数值（减少的时候数值前加上负号，如-100）
			 			"curpoint" =>  $uid["pay_points"],	//当前积分
			 			"whname"   =>  '首次注册送积分',	//操作者姓名，后台管理员或者前台会员
			 			"addtime"  =>	time(), 			//	addtime	
			 		
			 		 ];
				Db::table("ys_user_point_log")->insert($datapoint);
		    	session('_user_uid_',$data);
			}else{
				Db::table("ys_user")->where("mobile",$post["mobile"])
				         ->update(["openid"=>session('openid')]);
				
			}
			
			$wein = new WeixinService();
				$userinfo = Db::table("ys_user")->where("mobile",$post["mobile"])->find();
				// dd($userinfo["pay_code"].$userinfo["nickname"]);
				// die;
				$array = [
					 "type"   	  =>1,
					 "touser" 	  =>$userinfo["openid"],     
		          	 "template_id"=>Config::get("mobanid.huiyuan")["tempid"],
		          	 "url" 		  =>Config::get("mobanid.huiyuan")["url"],   
		          	 "topcolor"  =>"#743A3A",       
		           	 "data"   =>[
			                  	  "first" 			=>["value"=>"恭喜注册成功",        		"color"=>"#743A3A"],
			                  	   "keyword1"		=>["value"=>$userinfo["pay_code"], 		"color"=>"#743A3A"],
			                  	   "keyword2"		=>["value"=>$userinfo["nickname"], 		"color"=>"#743A3A"],
			                  	   "keyword3"		=>["value"=>$userinfo["mobile"], 		"color"=>"#743A3A"],
			                  	   "keyword4"		=>["value"=>date("Y-m-d",$userinfo["addtime"]),"color"=>"#743A3A"],
			                  	   "remark"			=>["value"=>"  感谢您的注册", 			"color"=>"#743A3A"],
		             ]
				];

			
			$rest  = $wein->sendmsg($array);
			$this->redirect('index/index/index');
		}
		return view('outlo/binduser');
	}

	/**
	 * 登录，在没登录的控制器中
	 * @return [type] [description]
	 */
	public function login() {
		if($post = input('post.')){
			$user = Db::table("ys_user")->where("mobile",$post['tele'])->find();
			if(!is_null($user)){
				if($user['password'] ==MD5($post['password'])){
					$data =["mobile"   => $user['mobile'],
							"password" => $user['password'],
							'openid'   => $user['openid'],
							"uid"      => $user['uid'],];
					session('_user_uid_',$data);
                    $this->redirect('index/index');
				}else{
					$this->error('密码或账户错误');
				}
			}else{
				$this->error('没有该账户，请先注册');
			}
		}
		return view('index/index');
	}


	/**
	 * 退出登录
	 */
	public function logout() {
		session('_user_uid_',null);
		$this->redirect('index/index');
	}



	/**
	 * 注册
	 */
	public function register() {
		if($post = input('post.')){
			if(empty($post['mobile'])) return view('user/register');
			if(empty($post['password'])) return view('user/register');
			$db =Db::table("ys_user")->where("mobile",$post['mobile'])->find();
			if(is_null($db)){
				$mypoint = (new PointService())->Point(1);
				$data=[	'mobile'     =>  $post['mobile'],
				   		'password' 	 =>  MD5($post['password']),
				    	'addtime' 	 =>  time(),
				    	"pay_points" =>	$mypoint["point"],
				   		'pay_code' 	 =>  rand(1000,9999).time(),
				   		"level_point"=> $mypoint["point"],
				    ];
				 if(!empty(session("sharer"))){
				 	$data["pid"] = session("sharer");
				 }
				//首次注册送积分
				Db::table("ys_user")->insert($data);
				$uid = Db::table("ys_user")->where("mobile",$post["mobile"])->find();
					$datapoint = [
				 			"uid"      =>  $uid["uid"],
				 			"uidtype"  =>  1,	    			//1.为前台自己注册，2位后台操作.3推荐好友获得
				 			"signid"   =>  $mypoint["id"], 	    //积分规则id
				 			"type"     =>  1,					//类型，0消费，1增加
				 			"point"    =>  $mypoint["point"],	//变更积分数值（减少的时候数值前加上负号，如-100）
				 			"curpoint" =>  $uid["pay_points"],	//当前积分
				 			"whname"   =>  '首次注册送积分',	//操作者姓名，后台管理员或者前台会员
				 			"addtime"  =>	time(), 			//	addtime	
				 			
				 		 ];
				//积分
				Db::table("ys_user_point_log")->insert($datapoint);
		    	$data["uid"] = $uid["uid"];
		    	//推荐送积分
		    	if(!empty(session("sharer"))){
		    		$pint = (new PointService())->Point(4);
				 	$pid 	= 	session("sharer");
				 	$user = (new PointService())->User($pid);
				 	Db::table("ys_user")->where("uid",$pid)->setInc("pay_points",$pint["point"]);
				 	Db::table("ys_user")->where("uid",$pid)->setInc("level_point",$pint["point"]);
				 	$datapoint = [
			 			"uid"      =>  $pid,
			 			"uidtype"  =>  3,	    			//1.为前台自己注册，2位后台操作.3推荐好友获得
			 			"signid"   =>  $pint["id"], 	    //积分规则id
			 			"type"     =>  1,					//类型，0消费，1增加
			 			"point"    =>  $pint["point"],		//变更积分数值（减少的时候数值前加上负号，如-100）
			 			"curpoint" =>  $user["pay_points"],	//当前积分
			 			"whname"   =>  '推荐好友的积分',	//操作者姓名，后台管理员或者前台会员
			 			"addtime"  =>	time(), 			//	addtime	
			 			//"tujianrenuid" =>$uid["uid"]
				 	 ];
				 	//积分
				 	Db::table("ys_user_point_log")->insert($datapoint);
				}
		    	session('_user_uid_',$data);
		    	$this->redirect('index/index/index'); 
			}else{
				$this->error('已经注册过，请登录');
			}	
		    
		}
		 return view('outlo/register');
	}

	/**
	 * 发送短信获取验证码
	 */
	public function getcord(){
		$mobile =request()->get("mobile");
		$code=rand(100000,999999);
		$code = 123456;
		Cache::set($mobile.'sms_code',$code,600);
		$this->success('发送成功');
		//return json(['status'=>1,"msg"=>"发送成功"]);
		$response = \SMS::sendSms(
            "阿里云短信测试专用", // 短信签名
            "SMS_112800049", // 短信模板编号
            $mobile, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"=>$code,
            ) 
        );
        if ($response->Code == 'OK' ) {
            Cache::set($mobile.'sms_code',$code,600);
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }
	}

	/**
	 * 验证码是否可用
	 */
	public function cordvertiy(){
		$mobile =request()->get("mobile");
		$cord =request()->get("cord");
		//return $mobile;
		//return json(Cache::get($mobile.'sms_code'));
		if( Cache::get($mobile.'sms_code')==$cord){
			return 1;
		}else{
			return 0;
		}
	}


	/**
	 * 门店开户，绑定微信号码
	 */
	public function blindweixin(){
		return view('outlo/blindweixin');
	}

	/**
	 * test
	 */
	public function test(){
		  $adminUserService = 	new SysToolsLevePoint;
		  $list = $AdminUserService->jifenjisuan(100000);
	}

	/**
	 * 保存用户信息
	 */
	public function saveuserinfo(){
		if (request()->isPost()){
			$post = $this->request -> post();
			//dd(session('_user_uid_'));
			//dd($post);die;
			$userservice = new UserService();
			$res = $userservice ->saveuserinfo($post);
			$this->redirect('user/index');
		}

		$userinfo = Db::table("ys_user")->where("uid",session('_user_uid_')['uid'])->find();

		return view('outlo/userinfo',['info'=>$userinfo]);
	}

	//随机生成32位
	public function getRandom($param){
	    $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	    $key = "";
	    for($i=0;$i<$param;$i++)
	     {

	         $key .= $str{mt_rand(0,32)};    //生成php随机数
	     }
	     return $key;
	 }

    /**
     * @Author  lignyun
     * @Desc    找回密码
     */
    public function find_password(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            if(empty($post['mobile'])){
                $this->error('请输入手机号','');
            }
            $user = db('user')->where('mobile',$post['mobile'])->find();
            if(empty($user)){
                $this->error('该手机号未被注册，请重新填写','');
            }
            if(empty($post['verify_code'])){
                $this->error('请输入验证码','');
            }
            if(empty($post['password'])){
                $this->error('请输入密码','');
            }
            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致，请重新填写','');
            }
            $reg = "/^[0-9a-zA-Z_]{6,16}$/";
            if(!preg_match($reg,$post['password'])){
                $this->error('密码格式不正确，只能是字母数字下划线6~16位组合','');
            }
            if($user['verify_code'] != $post['verify_code']){
                $this->error('验证码输入不正确','');
            }
            if($user['send_time']+3600<time()){
                $this->error('验证码已过期，请重新再试','');
            }
            $data['password'] = md5($post['password']);
            $result = db('user')->where('mobile',$post['mobile'])->data($data)->update();
            if($result !== false){
                session('_user_uid_',$user);
                $this->success('密码重置成功','');
            }else{
                $this->error('密码重置失败，请重试','');
            }
        }else{
            return $this->fetch('find_password');
        }
    }

    /**
     * @Author  lignyun
     * @Desc    获取短信验证码
     */
    public function get_verify_code(){
        $post = input('post.');
        $where_user['mobile'] = ['eq',$post['mobile']];
        $member = db('user')->where($where_user)->find();
        if(empty($member)){
            $this->error('找不到会员信息，请重试','');
        }
        $time = time();
        if(!empty($member['send_time']) && ($member['send_time']+60>$time)){
            $this->error('请在1分钟之后重新发送短信验证','');
        }else{
            $code=rand(100000,999999);
            $response = \SMS::sendSms(
                "雨泪", // 短信签名
                "SMS_86680176", // 短信模板编号
                $post['mobile'], // 短信接收者
                Array(  // 短信模板中字段的值
                    "code"=>$code,
                )
            );
            if ($response->Code == 'OK' ) {
                $where_user['mobile'] = ['eq',$post['mobile']];
                $data_arr = [
                    'verify_code'=>$code,
                    'send_time'=>time()
                ];
                db('user')->where($where_user)->data($data_arr)->update();
                $this->success('发送成功','');
            } else {
                halt($response->Code);
                $this->error('发送失败','');
            }
        }
    }

}